package io.renren.modules.gaokaobaobei.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.common.utils.Constant;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.gaokaobaobei.dao.UserBackupDao;
import io.renren.modules.gaokaobaobei.entity.UserBackupEntity;
import io.renren.modules.gaokaobaobei.service.UserBackupService;
import io.renren.modules.school.entity.*;
import io.renren.modules.student.entity.StudentProfession;
import io.renren.modules.student.service.StudentService;
import io.renren.modules.sys.shiro.ShiroUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static io.renren.modules.sys.shiro.ShiroUtils.getUserId;


@Service("userBackupService")
public class UserBackupServiceImpl extends ServiceImpl<UserBackupDao, UserBackupEntity> implements UserBackupService {

    @Autowired
    UserBackupDao userBackupDao;
    @Autowired
    StudentService studentService;

    @Override
    public PageUtils queryPage(Map<String, Object> params, String type) {
        String username = ShiroUtils.getSessionAttribute("username") + "";
        String isDesign = (String) params.get("isDesign");
        String search = (String) params.get("search");
        Page<UserBackupEntity> page = this.selectPage(
                new Query<UserBackupEntity>(params).getPage(),
                new EntityWrapper<UserBackupEntity>()
                        .like(StringUtils.isNotBlank(username), "username", username)
                        .like(StringUtils.isNotBlank(search), "username", search)
                        .like(StringUtils.isNotBlank(search), "phone", search)
                        .eq(StringUtils.isNotBlank(type), "type", type)
                        .eq(StringUtils.isNotBlank(isDesign), "is_design", isDesign)
                        .orderBy("id", false)
                        .addFilterIfNeed(params.get(Constant.SQL_FILTER) != null, (String) params.get(Constant.SQL_FILTER))
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils getSelfStudentlist(Map<String, Object> params) {
        Long userId = getUserId();
        String search = (String) params.get("search");
        String expertVisible = (String) params.get("expertVisible");
        Page<UserBackupEntity> page;
        if (expertVisible == null || expertVisible == "") {
            page = this.selectPage(
                    new Query<UserBackupEntity>(params).getPage(),
                    new EntityWrapper<UserBackupEntity>()
                            .like(StringUtils.isNotBlank(search), "name", search)
                            .orderBy("id", false)
                            .eq(StringUtils.isNotBlank(userId.toString()), "user_id", userId)
                            .addFilterIfNeed(params.get(Constant.SQL_FILTER) != null, (String) params.get(Constant.SQL_FILTER))
            );
        } else {
            page = this.selectPage(
                    new Query<UserBackupEntity>(params).getPage(),
                    new EntityWrapper<UserBackupEntity>()
                            .like(StringUtils.isNotBlank(search), "name", search)
                            .orderBy("id", false)
                            .eq(StringUtils.isNotBlank(expertVisible), "expert_visible", expertVisible)
                            .addFilterIfNeed(params.get(Constant.SQL_FILTER) != null, (String) params.get(Constant.SQL_FILTER))
            );
        }


        return new PageUtils(page);
    }

    @Override
    public UserBackupEntity getUserBackupByStudentId(Integer id) {
        UserBackupEntity student = userBackupDao.getUserBackupByStudentId(id);
        return student;
    }

    @Override
    public List<UserBackupEntity> getAllDataByUsername(String username) {
        return baseMapper.getAllDataByUsername(username);
    }

    @Override
    public int findTypeByUserName(Map<String, String> map) {
        return baseMapper.findTypeByUserName(map);
    }

    @Override
    public UserBackupEntity getByNameAndPhone(UserBackupEntity userBackup) {
        return userBackupDao.getByNameAndPhone(userBackup);
    }

    @Override
    public UserBackupEntity getNewUserBackup() {
        return userBackupDao.getNewUserBackup();
    }

    @Override
    public List<TreeEntity> getTemplatelTree(String username) {
        return userBackupDao.getTemplatelTree(username);
    }

    @Override
    public void saveTemplate(TemplateStudentEntity templateStudentEntity) {
        userBackupDao.saveTemplate(templateStudentEntity);
        Integer id = userBackupDao.getNewTempalte();
        int i = 1;
        for (UniversityEntity universityEntity : templateStudentEntity.getUniversitys()) {
            if (!"".equals(universityEntity.getName())) {
                universityEntity.setUserBackId(id);
                universityEntity.setSort(i);

                i++;
                saveTemplateUniversity(universityEntity);
            }
        }
        System.out.println();
    }

    @Override
    public List<UniversityEntity> getTemplateById(Integer id) {
        List<UniversityEntity> list = userBackupDao.getTemplateUniversityEntityById(id);
        List<UniversityEntity> returnList = new ArrayList<>();
        int num = 12;
        if (list != null) {
            num = 12 - list.size();
        }
        for (UniversityEntity u : list) {
            u.setProfessions(userBackupDao.getProfessionByUserBackId(u.getId(), id));
            returnList.add(u);
        }
        for (int i = 0; i < num; i++) {
            UniversityEntity u = new UniversityEntity();
            u.setName("");
            u.setCode("");
            u.setProfessions(new ArrayList<StudentProfession>());
            returnList.add(u);
        }
        return returnList;
    }

    @Override
    public List<UniversityEntity> getStudentDesign(Integer studentId) {
        List<UniversityEntity> list = userBackupDao.getStudentDesignById(studentId);
        List<UniversityEntity> returnList = new ArrayList<>();
        int num = 12;
        if (list != null) {
            num = 12 - list.size();
        }
        for (UniversityEntity u : list) {
            u.setProfessions(userBackupDao.getStudentDesignProfessionByUserBackId(u.getId(), studentId));
            returnList.add(u);
        }
        for (int i = 0; i < num; i++) {
            UniversityEntity u = new UniversityEntity();
            u.setName("");
            u.setCode("");
            u.setProfessions(new ArrayList<StudentProfession>());
            returnList.add(u);
        }
        return returnList;
    }

    @Override
    public void deleteStudentSchoolAndProfession(Integer id) {
        userBackupDao.deleteStudentSchool(id);
        userBackupDao.deleteStudentProfession(id);
    }

    @Override
    public void saveTuijian(UserBackupEntity userBackup) {
        UserBackupEntity saveUserBackup = new UserBackupEntity();
        saveUserBackup.setWantToDoRequest(userBackup.getWantToDoRequest());
        saveUserBackup.setNature1(userBackup.getNature1());
        System.out.println(userBackup.getWantToDoRequest());
        UserBackupEntity hasId = userBackupDao.selectOne(userBackup);
        List<String> natureList = userBackup.getNature1();
        List<String> forAppend = null;
        if (natureList.size() > 0) {
            forAppend = userBackupDao.getNatureProfressionList(natureList);
        }
        Integer id = hasId.getId();

        List<SchoolPredictor> list = new ArrayList<>();
        String[] studentProfessins = userBackup.getWantToDoRequest().split(",");

        if (studentProfessins.length > 0) {
            userBackup.setWantToDoRequest(studentProfessins[0]);
            list = userBackupDao.getUniversityEntityByProfession(userBackup);
            if (list.size() < 12) {
                if (studentProfessins.length > 1) {
                    for (int p = 1; p < studentProfessins.length; p++) {
                        if (list.size() < 12) {
                            userBackup.setWantToDoRequest(studentProfessins[p]);
                            List<SchoolPredictor> list1 = userBackupDao.getUniversityEntityByProfession(userBackup);
                            if (list1.size() > 0)
                                list.addAll(list1);
                            list = removeRepeat(list);
                        }
                    }
                }
            }
        }

        //根据各种条件搜索学校

        //如果初始条件没能搜满12所学校，将性格专业拼接到wtdrList上，增加专业条件，再次搜索
        if (list.size() < 12) {
            if (forAppend != null) {
                for (int fasize = 0; fasize < forAppend.size(); fasize++) {
                    String[] thisAppendProession = forAppend.get(fasize).split(",");

                    userBackup.setWantToDoRequest(thisAppendProession[0]);
                    List<SchoolPredictor> list2 = userBackupDao.getUniversityEntityByProfession(userBackup);
                    if (list2.size() > 0)
                        list.addAll(list2);
                    list = removeRepeat(list);
                    if (list.size() < 12) {
                        if (thisAppendProession.length > 1) {
                            for (int p = 1; p < thisAppendProession.length; p++) {
                                if (list.size() < 12) {
                                    userBackup.setWantToDoRequest(thisAppendProession[p]);
                                    List<SchoolPredictor> list1 = userBackupDao.getUniversityEntityByProfession(userBackup);
                                    if (list1.size() > 0)
                                        list.addAll(list1);
                                    list = removeRepeat(list);
                                }
                            }
                        }
                    }

                }
            }
        }
        //如果学校还是不够12所，去除城市限制，扩大搜索范围搜索
        if (list.size() < 12) {
            userBackup.setCity(null);
            List<SchoolPredictor> list1 = userBackupDao.getUniversityEntityByProfession(userBackup);
            if (list1.size() != 0)
                list.addAll(list1);
            list = removeRepeat(list);
        }
        //去除省市限制
        if (list.size() < 12) {
            userBackup.setProvince(null);
            List<SchoolPredictor> list2 = userBackupDao.getUniversityEntityByProfession(userBackup);
            if (list2.size() != 0)
                list.addAll(list2);
            list = removeRepeat(list);
        }
        //去除专业限制
        if (list.size() < 12) {
            userBackup.setWantToDoRequest(null);
            List<SchoolPredictor> list4 = userBackupDao.getUniversityEntityByProfession(userBackup);
            if (list4.size() != 0)
                list.addAll(list4);
            list = removeRepeat(list);
        }

        //防止学校数量超标，去除12个学校往后的学校
        if (list.size() > 12) {
            List<SchoolPredictor> finalList = new ArrayList<>();
            int i=0;
            add:for (SchoolPredictor schoolPredictor:list){
                if(i<12){
                    finalList.add(schoolPredictor);
                }else{
                    break add;
                }
                i++;
            }
            list.clear();
            list.addAll(finalList);
        }

        List<UniversityEntity> universityEntitys = new ArrayList<>();
        List<ProfessionEntity> studentProfessionList = studentService.getProfessionListByUniversityIds(list);
        for (int i = 0; i < list.size(); i++) {
            UniversityEntity u = new UniversityEntity();
            // SchoolPredictor[] schoolPredictors = (SchoolPredictor[]) list.toArray();
            SchoolPredictor[] schoolPredictors = new SchoolPredictor[12];
            for (int is = 0; is < list.size(); is++) {
                schoolPredictors[is] = list.get(is);
            }
            u.setUserBackId(id);
            u.setCode(schoolPredictors[i].getCode());
            u.setName(schoolPredictors[i].getName());
            u.setSort(i + 1);
            //todo 设置六个专业 利用循环找寻专业
            List<StudentProfession> studentProfessionList1 = new ArrayList<>();
            //当前学校全部专业
            List<ProfessionEntity> thisSchoolProfession = new ArrayList<>();
            int thisSchoolId = schoolPredictors[i].getId();
            for (ProfessionEntity professionEntity : studentProfessionList) {
                int thisProfessionSchoolId = professionEntity.getSchoolId();
                if (thisSchoolId == thisProfessionSchoolId) {
                    thisSchoolProfession.add(professionEntity);
                }
            }
            List<StudentProfession> thisSchoolFinalProfessionList = orderByUserBackup(thisSchoolProfession, saveUserBackup, forAppend);
//            saveUserBackup
            for (int j = 0; j < thisSchoolFinalProfessionList.size(); j++) {
                StudentProfession studentProfession = new StudentProfession();
                studentProfession.setUserBackId(id);
                studentProfession.setSort(j + 1);
                studentProfession.setName(thisSchoolFinalProfessionList.get(j).getName());
                studentProfession.setCode(thisSchoolFinalProfessionList.get(j).getCode());
                studentProfessionList1.add(studentProfession);
            }

            System.out.println(studentProfessionList1.toString());
            u.setProfessions(studentProfessionList1);
            studentService.saveStudentUniversity(u);
        }

    }

    private List<StudentProfession> orderByUserBackup(List<ProfessionEntity> thisSchoolProfession, UserBackupEntity saveUserBackup, List<String> forAppend) {
        String[] wantToDoRequestList = saveUserBackup.getWantToDoRequest().split(",");
        List<String> natureProfessionList = forAppend;
        int a = 0;
        List<Integer> lastOne = new ArrayList<>();
        List<StudentProfession> forReturn = new ArrayList<>();
        for (ProfessionEntity professionEntity : thisSchoolProfession) {
            String thisProfessionName = professionEntity.getName();
            if (wantToDoRequestList.length > 0) {
                for (int i = 0; i < wantToDoRequestList.length; i++) {
                    if (thisProfessionName.contains(wantToDoRequestList[i])) {
                        StudentProfession ts = new StudentProfession();
                        ts.setName(professionEntity.getName());
                        ts.setCode(professionEntity.getCode());
                        forReturn.add(ts);
                        lastOne.add(a);
                    }
                }
            }
            if (forReturn.size() < 6) {
                if (natureProfessionList != null) {
                    for (int i = 0; i < natureProfessionList.size(); i++) {
                        String[] thisAppendProession = natureProfessionList.get(i).split(",");
                        for (int l = 0; l < thisAppendProession.length; l++) {
                            if (thisProfessionName.contains(thisAppendProession[l])) {
                                StudentProfession ts = new StudentProfession();
                                ts.setName(professionEntity.getName());
                                ts.setCode(professionEntity.getCode());
                                forReturn.add(ts);
                                lastOne.add(a);
                            }
                        }
                    }
                }
            }
            a++;
        }

        if (forReturn.size() < 6) {
            for (int q = 0; q < lastOne.size(); q++) {
                thisSchoolProfession.remove(lastOne.get(q));
            }
            for (ProfessionEntity professionEntity : thisSchoolProfession) {
                if (forReturn.size() < 6) {
                    StudentProfession ts = new StudentProfession();
                    ts.setName(professionEntity.getName());
                    ts.setCode(professionEntity.getCode());
                    forReturn.add(ts);
                } else {
                    break;
                }
            }
        }
        List<StudentProfession> finalReturn = new ArrayList<>();
        if (forReturn.size() > 6) {
            int length = forReturn.size();
            for (int i = 0; i < 6; i++) {
                finalReturn.add(forReturn.get(i));
            }
            return finalReturn;
        }
        return forReturn;
    }

    private List<SchoolPredictor> removeRepeat(List<SchoolPredictor> list) {
       Set mark = new HashSet();
       List<SchoolPredictor> finalList = new ArrayList<>();
       for(SchoolPredictor schoolPredictor:list){
           if( mark.add(schoolPredictor.getId())){
               finalList.add(schoolPredictor);
           }
       }
        return finalList;
    }

    private void saveTemplateUniversity(UniversityEntity universityEntity) {
        userBackupDao.saveTemplateUniversity(universityEntity);
        UniversityEntity universityEntity1 = userBackupDao.getNewsTemplateUniversity();
        List<StudentProfession> professionEntities = universityEntity.getProfessions();
        int i = 1;
        for (StudentProfession professionEntity : professionEntities) {
            if (!"".equals(professionEntity.getName())) {
                professionEntity.setSchoolId(universityEntity1.getId());
                professionEntity.setSort(i);
                professionEntity.setUserBackId(universityEntity.getUserBackId());
                i++;
                userBackupDao.saveTemplateProfession(professionEntity);
                System.out.println("");
            }
        }

        System.out.println("");


    }

    @Override
    public boolean updateTypeByUserName(Map map) {
        return baseMapper.updateTypeByUserName(map);
    }

}
